// index.js
// 获取应用实例
const app = getApp()
const { connect }=require('../../utils/mqtt')
const mqttHost='broker.emqx.io'//mqtt服务器域名
const mqttPort='8084'//mqtt服务器端口
const deviceSubTopic='/mysmarthome/jxy'//设备订阅topic(小程序发布命令的topic)
const devicePubTopic='/mysmarthome/xy'//设备发布topic(小程序订阅命令的topic)

const mpSubTopic=deviceSubTopic
const mpPubTopic=devicePubTopic
Page({
  data: {
    client:null,
    Temp:0,
    Hum:0,
    Led:false,
    Buzzer:false
  },
  // 事件处理函数
    onShow() {
      const that =this
      that.setData({
        //wxs实际上就是wss=>wss实际上就是拥有SSL加密通信大的websockect协议
        client: connect(`wxs://${mqttHost}:${mqttPort}/mqtt`)
      })
      that.data.client.on('connect',function(params){
        console.log('成功连接到MQTT服务器！');
        wx.showToast({
          title: '连接成功',
          icon:'success',
          mask:true
        })
        that.data.client.subscribe(mpSubTopic,function(err)
        {
          if(!err){
            console.log('成功订阅设备上行数据topic！')
            
          }
        })
     })
     that.data.client.on('message',function(topic,message){
       console.log(topic);
       //message是16进制的buffer字节流
       let dataFromDev={}
      try {
        dataFromDev=JSON.parse(message)
        console.log(dataFromDev);
        that.setData(
            {
              Temp:dataFromDev.Temp,
              Hum:dataFromDev.Hum,
              Led:dataFromDev.Led,
              Buzzer:dataFromDev.Buzzer,
            })
      } catch (error) {
        //console.log(error);
        console.log('JSON解析失败',error);

      }

     })
   
  },
  onLedChange(event){
    const that=this
    console.log(event.detail);
    const sw=event.detail.value;
    that.setData({Led:sw})
    if(sw)
    {
      that.data.client.publish(mpPubTopic,JSON.stringify({
        target:"Led",
        value:1
      }),function(error){
        if(!error)
        {
          console.log('成功下发指令-开灯');
        }
      })
    }else{
      that.data.client.publish(mpPubTopic,JSON.stringify({
        target:"Led",
        value:0
      }),function(error){
        if(!error)
        {
          console.log('成功下发指令-关灯');
        }
      })

    }
  },
  onBuzzerChange(event){
    const that=this
    console.log(event.detail);
    const sw=event.detail.value;
    that.setData({Buzzer:sw})
    if(sw)
    {
      that.data.client.publish(mpPubTopic,JSON.stringify({
        target:"Buzzer",
        value:1
      }),function(error){
        if(!error)
        {
          console.log('成功下发指令-打开报警器');
        }
      })
    }else{
      that.data.client.publish(mpPubTopic,JSON.stringify({
        target:"Buzzer",
        value:0
      }),function(error){
        if(!error)
        {
          console.log('成功下发指令-关闭报警器');
        }
      })

    }
  }
})
